package com.config.shiro;

import com.pojo.User;
import com.service.PermissionService;
import com.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.List;

public class DBRealm extends AuthorizingRealm {

    @Resource
    private PermissionService permissionService;

    @Resource
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1.调用service中查询用户权限的方法
        List<String> stringList = permissionService.queryUserPermission();
        //2.创建SimpleAuthorizationInfo,将该用户具有的权限存入到该对象中
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(stringList);
        System.out.println("这是UserDBReam中拥有的权限"+stringList);
        //3.返回info，相当于将该用户的权限返回给了Subject对象
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1.从AuthenticationToken中取出来控制器传过来的用户信息
        String phone = (String) token.getPrincipal();
        //2.根据phone去查询
        User user = userService.selectByphone(phone);
        if(user == null){
            return null;
        }
        SimpleAuthenticationInfo info =
                new SimpleAuthenticationInfo(
                        user,
                        user.getPassword(),
                        ByteSource.Util.bytes(user.getSalt()),
                        user.getPhone());
        return info;
    }

}
